package pl.s7n.paint.edits;

import java.awt.Graphics2D;
import java.awt.Shape;
import java.util.ArrayList;

import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.UndoableEditSupport;

import pl.s7n.paint.commands.AbstractStrokeCmd;
import pl.s7n.paint.utils.Redrawable;

public class DrawingEditManager extends AbstractEditManager<AbstractStrokeCmd> {
  private static final long serialVersionUID = 2770227705271506939L;

  private Redrawable        parent;

  public DrawingEditManager(UndoableEditSupport undoableEditSupport, Redrawable parent) {
    super(undoableEditSupport);
    this.parent = parent;
    actions = new ArrayList<AbstractStrokeCmd>();
  }

  public void draw(Graphics2D g) {
    Shape clip = g.getClip();
    for (AbstractStrokeCmd action : actions) {
      action.draw(g);
      g.setClip(clip);
    }
  }

  public void editPerformed(AbstractStrokeCmd action) {
    super.editPerformed(action);
    undoableEditSupport.postEdit(new DrawingEdit(action));
  }

  private class DrawingEdit extends AbstractUndoableEdit {
    private static final long serialVersionUID = 335755372811578290L;

    AbstractStrokeCmd         newAction;

    public DrawingEdit(AbstractStrokeCmd newAction) {
      this.newAction = newAction;
    }

    @Override
    public String getRedoPresentationName() {
      return "Redo " + newAction.toString();
    }

    @Override
    public String getUndoPresentationName() {
      return "Undo " + newAction.toString();
    }

    @Override
    public void undo() {
      super.undo();
      actions.remove(newAction);
      parent.redraw();
    }

    @Override
    public void redo() {
      super.redo();
      actions.add(newAction);
      parent.redraw();
    }
  }
}
